<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category	CosmoCommerce
 * @package 	CosmoCommerce_CreditCard
 * @copyright	Copyright (c) 2009 CosmoCommerce,LLC. (http://www.cosmocommerce.com)
 * @contact :
 * T: +86-021-66346672
 * L: Shanghai,China
 * M:sales@cosmocommerce.com
 */
class Globebill_Qiwi_PaymentController extends Mage_Core_Controller_Front_Action
{
	/**
	 * Order instance
	 */
	protected $_order;

	/**
	 *  Get order
	 *
	 *  @param    none
	 *  @return	  Mage_Sales_Model_Order
	 */
	public function getOrder()
	{	
		//从session获取isrepayment是否重新支付和orderid订单号，烈
		$isRePayment = Mage::getSingleton("core/session")->getData("isrepayment");
		$IncrementId = Mage::getSingleton("core/session")->getData("repay_IncrementId");

		if ($this->_order == null) {
			$session = Mage::getSingleton('checkout/session');			
			$this->_order = Mage::getModel('sales/order');
			//这里判断是否为重新支付，烈
			if(!$isRePayment){
				$this->_order->loadByIncrementId($session->getLastRealOrderId());
			}else{
				$this->_order->loadByIncrementId($IncrementId);
			}
		}
		return $this->_order;
	}

	/**
	 * When a customer chooses qiwi on Checkout/Payment page
	 *
	 */
	public function redirectAction()
	{
		$session = Mage::getSingleton('checkout/session');
		$session->setQiwiPaymentQuoteId($session->getQuoteId());

		$order = $this->getOrder();

		if (!$order->getId()) {
			$this->norouteAction();
			return;
		}

		$order->addStatusToHistory(
		$order->getStatus(),
		Mage::helper('qiwi')->__('Customer was redirected to Qiwi')
		);
		$order->save();

		$this->loadLayout();
		$this->getLayout()->getBlock('root')->setTemplate('page/1column.phtml');
		$this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('qiwi/redirect'));
		$this->renderLayout();


		$session->unsQuoteId();
	}

	/**
	 *  qiwi response router
	 *
	 *  @param    none
	 *  @return	  void
	 */
	public function notifyAction()
	{
		$model = Mage::getModel('qiwi/payment');

		if ($this->getRequest()->isPost()) {
			$postData = $this->getRequest()->getPost();
			$method = 'post';

		} else if ($this->getRequest()->isGet()) {
			$postData = $this->getRequest()->getQuery();
			$method = 'get';

		} else {
			$model->generateErrorResponse();
		}



		$order = Mage::getModel('sales/order')
		->loadByIncrementId($postData['reference']);

		if (!$order->getId()) {
			$model->generateErrorResponse();
		}

		if ($returnedMAC == $correctMAC) {
			if (1) {
				$order->addStatusToHistory(
				$model->getConfigData('order_status_payment_accepted'),
				Mage::helper('qiwi')->__('Payment accepted by Qiwi')
				);

				$order->sendNewOrderEmail();

				if ($this->saveInvoice($order)) {
					//                $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
				}

			} else {
				$order->addStatusToHistory(
				$model->getConfigData('order_status_payment_refused'),
				Mage::helper('qiwi')->__('Payment refused by Qiwi')
				);

				// TODO: customer notification on payment failure
			}

			$order->save();

		} else {
			$order->addStatusToHistory(
			Mage_Sales_Model_Order::STATE_CANCELED,//$order->getStatus(),
			Mage::helper('qiwi')->__('Returned MAC is invalid. Order cancelled.')
			);
			$order->cancel();
			$order->save();
			$model->generateErrorResponse();
		}
	}

	/**
	 *  Save invoice for order
	 *
	 *  @param    Mage_Sales_Model_Order $order
	 *  @return	  boolean Can save invoice or not
	 */
	protected function saveInvoice(Mage_Sales_Model_Order $order)
	{
		if ($order->canInvoice()) {
			$convertor = Mage::getModel('sales/convert_order');
			$invoice = $convertor->toInvoice($order);
			foreach ($order->getAllItems() as $orderItem) {
				if (!$orderItem->getQtyToInvoice()) {
					continue;
				}
				$item = $convertor->itemToInvoiceItem($orderItem);
				$item->setQty($orderItem->getQtyToInvoice());
				$invoice->addItem($item);
			}
			$invoice->collectTotals();
			$invoice->register()->capture();
			Mage::getModel('core/resource_transaction')
			->addObject($invoice)
			->addObject($invoice->getOrder())
			->save();
			return true;
		}

		return false;
	}
	/**
	 *  Success payment page
	 *
	 *  @param    none
	 *  @return	  void
	 */
	public function returnAction()
	{
		$model = Mage::getModel('qiwi/payment');
		if(isset($_REQUEST['isPush']) && $_REQUEST['isPush'] == '1'){         //检测是否推送 1为推送  空为正常POST
			$this->_order = Mage::getModel('sales/order');
			$order = $this->_order->loadByIncrementId($_REQUEST['orderNo']);    //载入order模块
			$logtype = '[GB->Merchant(PUSH)]';                //记录log类型
		}else{
			$order = $this->getOrder();         //载入order模块
			$logtype = '[GB->Merchant(Browser Return)]';              //记录log类型
		}
		
		//记录return log
		$this->returnlog($logtype);
		
		if($_REQUEST['isPush'] == '1'){
			switch($this->_validated()){
				case 1:
					//支付成功
    				$order->addStatusToHistory(
    				$model->getConfigData('order_status_payment_accepted'),
    				Mage::helper('qiwi')->__('(PUSH)Payment succeed!
    					      (tradeNo:'.$_REQUEST['tradeNo'].
    					     ' | orderNo:'.$_REQUEST['orderNo'].
    					     ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
    					     ' | orderInfo:'.$_REQUEST['orderInfo'].')'),true
    				);

					/*
    				Mage::log('出库推送功能开始, $_REQUEST["isPush"]为1, 支付类型为Qiwi.');
    				//出库推送功能（烈）
	    			try{
	               		$obj = Mage::helper('saleorderservice');
	                	$obj->pushOrderInfo($_REQUEST['orderNo'],$_REQUEST['tradeNo']);
			        }catch(Exception $e){
			        	echo $e->getMessage();
			        }
			        Mage::log('出库推送功能结束, $_REQUEST["isPush"]为1, 支付类型为Qiwi.');
					*/
					
    				$order->save();
					break;
				case 0:
					//支付失败
					$order->addStatusToHistory(
    				$model->getConfigData('order_status_payment_refused'),
    				Mage::helper('qiwi')->__('(PUSH)Payment failed!
    				        (tradeNo:'.$_REQUEST['tradeNo'].
    				        ' | orderNo:'.$_REQUEST['orderNo'].
    				        ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
    				        ' | orderInfo:'.$_REQUEST['orderInfo'].')')		
    				);
    				$order->save();
					break;
				case -1:
    				//交易待处理
    				$order->addStatusToHistory(
    				$model->getConfigData('order_status_payment_wait'),
    				Mage::helper('qiwi')->__('(PUSH)Payment Wait!
    					    (tradeNo:'.$_REQUEST['tradeNo'].
    					    ' | orderNo:'.$_REQUEST['orderNo'].
    					    ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
    					    ' | orderInfo:'.$_REQUEST['orderInfo'].')')
    				);
    				$order->save();
    				break;
    			case -2:
    				//交易待确认
    				break;
    			case 61:
    				//订单号重复
    				break;
    			case 999:
    				//加密值错误或系统异常
    				break;	
    			default:
			
			}			
			
		}elseif($_REQUEST['isPush'] == ''){
			//确保状态正确改变，推送失败时 POST返回也能修改状态

			//是否重新支付，重新支付不能跳转到checkout/onepage/success，跳转到自定义页面，烈
			if(!Mage::getSingleton("core/session")->getData("isrepayment"))
			{
				switch($this->_validated()){
					case 1:
						//支付成功
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_accepted'),
	    				Mage::helper('qiwi')->__('(POST)Payment succeed!
	    				         (tradeNo:'.$_REQUEST['tradeNo'].
	    				         ' | orderNo:'.$_REQUEST['orderNo'].
	    				         ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    				         ' | orderInfo:'.$_REQUEST['orderInfo'].')'),true
	    				);
						
						/*
	    				Mage::log('出库推送功能开始, $_REQUEST["isPush"]为空, 支付类型为Qiwi.');
	    				//出库推送功能（烈）
		    			try{
		               		$obj = Mage::helper('saleorderservice');
		                	$obj->pushOrderInfo($_REQUEST['orderNo'],$_REQUEST['tradeNo']);
				        }catch(Exception $e){
				        	echo $e->getMessage();
				        }
				        Mage::log('出库推送功能结束, $_REQUEST["isPush"]为空, 支付类型为Qiwi.');
				        */
						
	    				//发送邮件
	    				$order->sendNewOrderEmail();
	    				//自动Invoice
	    				if($model->getConfigData('automatic_invoice') == '1'){
	    					$this->saveInvoice($order);
	    				}
    				
	    				$order->save();
	    				$this->getResponse()
	    				     ->setBody($this->getLayout()
	    					 ->createBlock('qiwi/success')
	    					 ->setRedirectUrl(Mage::getUrl('checkout/onepage/success'))
	    					 ->toHtml());
						break;
					case 0:
						//支付失败
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_refused'),
	    				Mage::helper('qiwi')->__('(POST)Payment failed!
	    				        (tradeNo:'.$_REQUEST['tradeNo'].
	    				        ' | orderNo:'.$_REQUEST['orderNo'].
	    				        ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    				        ' | orderInfo:'.$_REQUEST['orderInfo'].')')		
	    				);
	    				$order->save();
	    				$this->getResponse()
	    				     ->setBody($this->getLayout()
	    					 ->createBlock('qiwi/failure')
	    					 ->setRedirectUrl(Mage::getUrl('checkout/onepage/failure'))
	    					 ->toHtml());
						break;
					case -1:
	    				//交易待处理
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_wait'),
	    				Mage::helper('qiwi')->__('(POST)Payment Wait!
	    					    (tradeNo:'.$_REQUEST['tradeNo'].
	    					    ' | orderNo:'.$_REQUEST['orderNo'].
	    					    ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    					    ' | orderInfo:'.$_REQUEST['orderInfo'].')')
	    					);
	    				$order->save();
	    				$this->getJslocationreplace(Mage::getUrl('qiwi/payment/wait'));
	    				break;
	    			case -2:
	    				//交易待确认
	    				$this->getJslocationreplace(Mage::getUrl('qiwi/payment/wait'));
	    				break;
	    			case 61:
	    				//订单号重复
	    				$this->getResponse()
	    				     ->setBody($this->getLayout()
	    					 ->createBlock('qiwi/failure')
	    					 ->setRedirectUrl(Mage::getUrl('checkout/onepage/failure'))
	    					 ->toHtml());
	    			case 999:
	    				//加密值错误或系统异常
	    				$this->getResponse()
	    				     ->setBody($this->getLayout()
	    					 ->createBlock('qiwi/failure')
	    					 ->setRedirectUrl(Mage::getUrl('checkout/onepage/failure'))
	    					 ->toHtml());
					default:
						$this->getResponse()
						     ->setBody($this->getLayout()
							 ->createBlock('qiwi/failure')
							 ->setRedirectUrl(Mage::getUrl('checkout/onepage/failure'))
							 ->toHtml());
				
				}
			}
			else   //重新支付，跳转到自定义页面，烈
			{
				switch($this->_validated()){
					case 1:
						//支付成功
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_accepted'),
	    				Mage::helper('qiwi')->__('(POST)Payment succeed!
	    				         (tradeNo:'.$_REQUEST['tradeNo'].
	    				         ' | orderNo:'.$_REQUEST['orderNo'].
	    				         ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    				         ' | orderInfo:'.$_REQUEST['orderInfo'].')'),true
	    				);
	    				//出库推送功能（烈）
		    			try{
		               		$obj = Mage::helper('saleorderservice');
		                	$obj->pushOrderInfo($_REQUEST['orderNo'],$_REQUEST['tradeNo']);
				        }catch(Exception $e){
				        	echo $e->getMessage();
				        }
				        
	    				$order->save();
	    				$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"success"));
						break;
					case 0:
						//支付失败
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_refused'),
	    				Mage::helper('qiwi')->__('(POST)Payment failed!
	    				        (tradeNo:'.$_REQUEST['tradeNo'].
	    				        ' | orderNo:'.$_REQUEST['orderNo'].
	    				        ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    				        ' | orderInfo:'.$_REQUEST['orderInfo'].')')		
	    				);
	    				$order->save();
	    				$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"failure"));
						break;
					case -1:
	    				//交易待处理
	    				$order->addStatusToHistory(
	    				$model->getConfigData('order_status_payment_wait'),
	    				Mage::helper('qiwi')->__('(POST)Payment Wait!
	    					    (tradeNo:'.$_REQUEST['tradeNo'].
	    					    ' | orderNo:'.$_REQUEST['orderNo'].
	    					    ' | '.$_REQUEST['orderCurrency'].':'.$_REQUEST['orderAmount'].
	    					    ' | orderInfo:'.$_REQUEST['orderInfo'].')')
	    					);
	    				$order->save();
	    				$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"wait"));
	    				break;
	    			case -2:
	    				//交易待确认
	    			    $this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"wait"));
	    				break;
	    			case 61:
	    				//订单号重复
	    				$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"failure"));
	    			case 999:
	    				//加密值错误或系统异常
	    				$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"failure"));
					default:
						$this->_redirect('orderrepayment/repayment/ifarmeRedirect',array("status"=>"failure"));
				
				}
			}
		}	
		
	}

	private function _validated()
	{
        //载入模块
		$model            = Mage::getModel('qiwi/payment');
		
		//载入session模块
		$session          = Mage::getSingleton('checkout/session');
		
		//获取订单
		$order            = $this->getOrder();
		
		//获取商户号
		$merNo            = $model->getConfigData('merchant_no');
		
		//返回网关接入号
		$gatewayNo        = $_REQUEST['gatewayNo'];
		
		//返回流水订单号
		$tradeNo          = $_REQUEST['tradeNo'];
		
		//返回网站订单号
		$orderNo          = $order->getRealOrderId();
		
		//返回交易币种
		$orderCurrency    = $order->getOrderCurrencyCode();
		
		//返回交易金额
		$orderAmount      = $_REQUEST['orderAmount'];
		
		//返回交易状态
		$orderStatus      = $_REQUEST['orderStatus'];
		
		//返回交易信息
	
		$orderInfo        = $_REQUEST['orderInfo'];
		$_SESSION['orderInfo'] = $orderInfo;
		$_SESSION['errorCode'] = substr($orderInfo,0,5);
		$_SESSION['check'] = strtolower($orderInfo);
		
		preg_match('/do not honour/si', $_SESSION['check'], $p);
		if(isset($p[0])){
			$_SESSION['donothonour'] = '1';
		}else{
			$_SESSION['donothonour'] = '0';
		};
		
		preg_match('/refer to card issuer/si', $_SESSION['check'], $p);
		if(isset($p[0])){
			$_SESSION['refertocardissuer'] = '1';
		}else{
			$_SESSION['refertocardissuer'] = '0';
		};


		//返回数据签名
		$signInfo         = $_REQUEST['signInfo'];
		
		//获取KEY
		$signkey          = $model->getConfigData('signkey_code');
		
		//SH256加密
		$signInfocheck    = hash("sha256" , $merNo . $gatewayNo . $tradeNo . $orderNo . $orderCurrency . $orderAmount . $orderStatus . $orderInfo . $signkey);
		
		//转换成大写
		$signInfocheck    = strtoupper($signInfocheck);
	    
		
		//是否点击浏览器后退造成订单号重复 I0061
		if(substr($orderInfo,0,5) == 'I0061'){
			return 61;
			exit;
		}

		//加密校验
		// if($signInfocheck == $signInfo){
			//支付状态
			if ($orderStatus == '1') {
				return 1;
			} elseif ($orderStatus == '-1') {
				return -1;
			} elseif ($orderStatus == '-2') {	
				return -2;
			} elseif ($orderStatus == '0') {
				return 0;
			} else{
				return 999;
			}
		// }else{
		// 	return 999;
		// }
		
	}

	
	/**
	 * return log
	 *
	 */
	public function returnlog($logtype){
	
		$filedate   = date('Y-m-d');
	
		$returndate = date('Y-m-d H:i:s');
			
		$newfile    = fopen( "globebill_log/" . $filedate . ".log", "a+" );
			
		$return_log = $returndate . $logtype . "\r\n".
				"isPush = "       . $_REQUEST['isPush'] . "\r\n".
				"merNo = "        . $_REQUEST['merNo'] . "\r\n".
				"gatewayNo = "    . $_REQUEST['gatewayNo'] . "\r\n".
				"tradeNo = "      . $_REQUEST['tradeNo'] . "\r\n".
				"orderNo = "      . $_REQUEST['orderNo'] . "\r\n".
				"orderCurrency = ". $_REQUEST['orderCurrency'] . "\r\n".
				"orderAmount = "  . $_REQUEST['orderAmount'] . "\r\n".
				"orderStatus = "  . $_REQUEST['orderStatus'] . "\r\n".
				"orderInfo = "    . $_REQUEST['orderInfo'] . "\r\n".
				"signInfo = "     . $_REQUEST['signInfo'] . "\r\n".
				"riskInfo = "     . $_REQUEST['riskInfo'] . "\r\n".
				"remark = "       . $_REQUEST['remark'] . "\r\n";
	
		$return_log = $return_log . "*************************************\r\n";
			
		$return_log = $return_log.file_get_contents( "globebill_log/" . $filedate . ".log");
			
		$filename   = fopen( "globebill_log/" . $filedate . ".log", "r+" );
			
		fwrite($filename,$return_log);
	
		fclose($filename);
	
		fclose($newfile);
	
	}
	
	/**
	 *  Success payment page
	 *
	 *  @param    none
	 *  @return	  void
	 */
	public function successAction()
	{
		$session = Mage::getSingleton('checkout/session');
		$session->setQuoteId($session->getCreditCardPaymentQuoteId());
		$session->unsCreditCardPaymentQuoteId();

		$order = $this->getOrder();

		if (!$order->getId()) {
			$this->norouteAction();
			return;
		}

		$order->addStatusToHistory(
		$order->getStatus(),
		Mage::helper('qiwi')->__('Customer successfully returned from Qiwi')
		);

		$order->save();

		$this->_redirect('checkout/onepage/success');
	}

	/**
	 *  Failure payment page
	 *
	 *  @param    none
	 *  @return	  void
	 */
	public function errorAction()
	{
		$session = Mage::getSingleton('checkout/session');
		$errorMsg = Mage::helper('qiwi')->__(' There was an error occurred during paying process.');

		$order = $this->getOrder();

		if (!$order->getId()) {
			$this->norouteAction();
			return;
		}
		if ($order instanceof Mage_Sales_Model_Order && $order->getId()) {
			$order->addStatusToHistory(
			Mage_Sales_Model_Order::STATE_CANCELED,//$order->getStatus(),
			Mage::helper('qiwi')->__('Customer returned from Qiwi.') . $errorMsg
			);

			$order->save();
		}

		$this->loadLayout();
		$this->renderLayout();
		Mage::getSingleton('checkout/session')->unsLastRealOrderId();
	}
	
	
	
	/**
	 *  Wait payment page
	 *
	 *  @param    none
	 *  @return	  void
	 */
	public function waitAction()
	{
		$this->loadLayout();
		$this->getLayout()->getBlock('root')->setTemplate('page/2columns-right.phtml');
		$this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('qiwi/wait'));
		$this->renderLayout();
	}
	
	/**
	 *  Wait payment page
	 *
	 */
	public function getJslocationreplace($url)
	{
		echo '<script type="text/javascript">parent.location.replace("'.$url.'");</script>';
		
	}
	
	
}
